#include "stdafx.h"
#include "SessionGroup.h"

#include "RuleModel.h"

#include "Session.h"
#include "ParallelSystem.h"

int CSessionGroup::s_generateSessionID = 0;

CSessionGroup::CSessionGroup(void)
{
}

CSessionGroup::~CSessionGroup(void)
{
}

void CSessionGroup::Initialize( int id, int count )
{
	m_groupID = id;

	Put( L"creating session group id[%d] session count[%d]", id, count );

	for( int i = 1 ; i <= count ; ++i )
	{
		CSession* newSession = new CSession;
		newSession->Initialize( this, i );
		m_mapSessions.insert( MAP_SESSIONS::value_type( newSession->GetSessioinID(),newSession) );
	}
	Put( L"creating completed!" );

	_PARALLEL_SYSTEM_::CParallelTask* task = new _PARALLEL_SYSTEM_::CParallelTask;
	task->Initialize( m_groupID, 1 );

	PARALLEL_SYSTEM.AddTask( task );

	m_finished_sessions = 0;
}

void CSessionGroup::DoWork()
{
	_PARALLEL_SYSTEM_::Job* job = new _PARALLEL_SYSTEM_::Job;
	job->m_completionHandler = nullptr;
	job->m_job = [ job, this ]()
	{
		while( 1 )
		{
			for each( const MAP_SESSIONS::value_type& value in m_mapSessions )
			{
				auto session = value.second;
				session->Update();
			}

			if( m_finished_sessions == m_mapSessions.size() )
			{
				Put(L"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
				Put(L" All Group Session Job Finished group[%d]", m_groupID );
				Put(L"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
			}

			::Sleep( 1 );
		}
	};

	PARALLEL_SYSTEM.PostJob( m_groupID, job );
}

void CSessionGroup::Close()
{

}

void CSessionGroup::JobFinished( int sessionID )
{
	m_finished_sessions++;
}